import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    goodsIdArr: JSON.parse(localStorage.getItem('car')) || []
  },
  mutations: {
    addGoodsIdArr(state, obj) {
      let flag = true
      state.goodsIdArr.forEach(item => {
        if (item.id === obj.id) {
          item.count += obj.count
          flag = false
        }
      })
      if (flag) {
        state.goodsIdArr.push(obj)
      }
      localStorage.setItem('car', JSON.stringify(state.goodsIdArr))
    },
    addCountById(state, id) {
      console.log(999)
      state.goodsIdArr.forEach(item => {
        if (item.id == id) {
          item.count++
        }
      })
      console.log(state.goodsIdArr)
      localStorage.setItem('car', JSON.stringify(state.goodsIdArr))
    },
    subCountById(state, id) {
      console.log(999)
      state.goodsIdArr.forEach(item => {
        if (item.id == id) {
          item.count--
        }
      })
      console.log(state.goodsIdArr)
      localStorage.setItem('car', JSON.stringify(state.goodsIdArr))
    },
    delCountById(state, id) {
      let index = state.goodsIdArr.findIndex(item => item.id == id)
      state.goodsIdArr.splice(index, 1)
      localStorage.setItem('car', JSON.stringify(state.goodsIdArr))
    }
  },
  actions: {},
  getters: {
    total(state) {
      let num = 0
      state.goodsIdArr.forEach(item => {
        num += item.count
      })
      return num
    }
  }
})
